<?php

namespace App\Logics;


use App\Models\Course;
use App\Models\CourseCycle;
use App\Service\Base\Logic;

class CourseCycleLogic extends Logic
{

    // 课程周期
    public function initialize()
    {
        parent::initialize();

        $this->model = 'CourseCycle';
    }

    // 列表
    // 添加
    // 修改


    // 列表查询
    public function onLists()
    {
        $option = $this->option();
        $page   = $option->getData('page', 1, 'intval');
        $rows   = $option->getData('rows', 15, 'intval');
        $isPage = $option->getData('is_count', 0, 'intval');  // 是否需要翻页
        $start  = ($page - 1) * $rows;

        // 模型 和 查询
        $where   = [];
        $bang    = [];
        $c_id    = $option->getData('course_id', 0, 'intval');
        $uid     = $option->getData('uid', 0, 'intval');
        $name    = $option->getData('name', null, 'trim');
        $keyword = $option->getData('keyword', null, 'trim');
        if($c_id){
            $bang[]  = 'id';
            $where[] = ['course_id', '=', $c_id];
        }
        if($uid){
            $bang[]  = 'uid';
            $where[] = ['uid', '=', $uid];
        }
        if($name){
            $bang    = false;
            $where[] = ['name', 'like', "%".$name."%"];
        }

        // 模型
        $model  = new CourseCycle();
        $KCache = $model->cacheKey('lists', $where);
        $result = $model->cacheClass()->getCache($KCache);
        // 检查是否已经绑定
        if(!empty($result)){
            if($isPage){
                if(!empty($result['list'])){
                    $model->checkBangList($result['list'], $KCache);
                }
            } else{
                $model->checkBangList($result, $KCache);
            }
        }

        // ->bangField($bang)
        if(empty($result)){
            if($isPage){
                $result = $model->listPage($where, $page, $rows, "id DESC");
            } else{
                $result = $model->getList($where, $rows, "id DESC", $start);
                $result = is_object($result) ? $result->toArray() : $result;
            }
            /*if($where != false){
                $model->addCacheList($lists, $KCache, $lists, 'list');
            }*/
        }

        return $result;
    }

    //   发布者的详情
    //   提醒我的课程详情
    //   上课时间
    public function onShow()
    {
        $option = $this->option();
        $c_id   = $option->getData('course_id', 0, 'intval');
        $_id    = $option->getData('id', 0, 'intval');  // 如果是学员，看自己的课程信息

        // 课程时间
        $timesDb = new CourseCycle();
        $times   = $timesDb->bangField(['course_id'])->oneFind(['id' => $_id]);
        if(empty($times)){
            return $this->_returnFail($timesDb->getError());
        }

        return $times;
    }


    // 直接删除
    public function onDelete($myUid)
    {
        $opt = $this->option();
        $_id = $opt->getData('id', 0, 'intval');
        if(empty($_id)){
            return $this->_returnFail('请指定删除记录');
        }

        $where  = ['id' => $_id, 'uid' => $myUid];
        $model  = new CourseCycle();
        $result = $model->isCache(true)->oneDelete($where);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }


    // 直接删除
    public function batchDelete($myUid)
    {
        $opt  = $this->option();
        $_ids = $opt->getData('ids', [], 'is_array');
        if(empty($_ids)){
            return $this->_returnFail('请指定删除记录');
        }

        $where = ['uid' => $myUid];
        $model = new CourseCycle();
        $list  = $model->whereIn('id', $_ids)->where($where)->get();  //->recycle()
        if($list->isEmpty()){
            return $this->_returnFail('你要删除的数据不存在！！');
        }

        // 缓存操作
        $model->deleteCacheList($list);
        $res = $model->whereIn('id', $_ids)->where($where)->delete();  //->recycle()

        return $res;
    }


    // 改变（直接修改，软删除，改变状态，排序）
    public function onEdit($myUid)
    {
        $opt = $this->option();
        $_id = $opt->getData('id', null, 'intval');
        if(empty($_id)){
            return $this->_returnFail('请指定修改的ID编号！');
        }

        $data = [
            //'id'         => $opt->getData("id", null, "trim"),
            //'uid'        => $myUid,
            'course_id'  => $opt->getData("course_id", null, "intval"),
            'cycle'      => $opt->getData("cycle", null, "trim"),
            'number'     => $opt->getData("number", null, "trim"),
            'start_time' => $opt->getData("start_time", null, "strtotime"),
            'end_time'   => $opt->getData("end_time", null, "strtotime"),
            //'ctime'      => $opt->getData("ctime", null, "trim"),
            //'mtime'      => $opt->getData("mtime", null, "trim"),
        ];
        if($data['end_time'] && ($data['end_time'] <= $data['start_time'])){
            return $this->_returnFail('结束时间不能小于开始时间！');
        }

        // 最终生成的时间戳 必须在一天之内
        // 但直接生成的时间戳 默认是当天 所以要减去当天的开始时间戳
        // 获取今天日期的开始时间戳
        $timestamp = strtotime("today");
        if($data['start_time'] > 86400){
            $data['start_time'] = $data['start_time'] - $timestamp;
        }
        if($data['start_time'] < -86400){
            $data['start_time'] = $data['start_time'] + $timestamp;
        }
        if($data['end_time']){
            if($data['end_time'] > 86400){
                $data['end_time'] = $data['end_time'] - $timestamp;
            }
            if($data['end_time'] < -86400){
                $data['end_time'] = $data['end_time'] + $timestamp;
            }
        }


        $data = $this->filterNull($data);
        if(empty($data)){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 组合数据
        $where = ['id' => $_id, 'uid' => $myUid];
        $model = new CourseCycle();
        $data  = $model->checkData($data, $where);
        if($data === false){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 验证
        $result = $model->checkRules($data, 'edit');
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 保存
        //  保存的时候：保存时间
        $result = $model->oneEdit($where, $data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    // 树状
    public function onAdd($myUid)
    {
        $opt  = $this->option();
        $data = [
            //'id'         => $opt->getData("id", null, "trim"),
            'uid'        => $myUid,
            'course_id'  => $opt->getData("course_id", null, "intval"),
            'cycle'      => $opt->getData("cycle", null, "trim"),
            'number'     => $opt->getData("number", null, "trim"),
            'start_time' => $opt->getData("start_time", null, "strtotime"),
            'end_time'   => $opt->getData("end_time", null, "strtotime"),
            //'ctime'      => $opt->getData("ctime", null, "trim"),
            //'mtime'      => $opt->getData("mtime", null, "trim"),
        ];

        if($data['end_time'] && ($data['end_time'] <= $data['start_time'])){
            return $this->_returnFail('结束时间不能小于开始时间！');
        }


        // 最终生成的时间戳 必须在一天之内
        // 但直接生成的时间戳 默认是当天 所以要减去当天的开始时间戳
        // 获取今天日期的开始时间戳
        $timestamp = strtotime("today");
        if($data['start_time'] > 86400){
            $data['start_time'] = $data['start_time'] - $timestamp;
        }
        if($data['start_time'] < -86400){
            $data['start_time'] = $data['start_time'] + $timestamp;
        }
        if($data['end_time']){
            if($data['end_time'] > 86400){
                $data['end_time'] = $data['end_time'] - $timestamp;
            }
            if($data['end_time'] < -86400){
                $data['end_time'] = $data['end_time'] + $timestamp;
            }
        }


        // 测试时间应该到当天晚上
        $data = $this->filterNull($data);
        if(empty($data)){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 组合数据
        $model = new CourseCycle();
        $data  = $model->checkData($data);
        if($data === false){
            return $this->_returnFail('请添加需要保存的数据！');
        }

        // 验证
        $result = $model->checkRules($data, 'add');
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 保存
        $result = $model->oneAdd($data);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }


    // 列表查询
    protected function listWhere()
    {
        $option  = $this->option();
        $where   = [];
        $bang    = [];
        $c_id    = $option->getData('course_id', 0, 'intval');
        $keyword = $option->getData('keyword', null, 'trim');
        if($c_id){
            $bang[]  = 'course_id';
            $where[] = ['course_id', '=', $c_id];
        }
        if($keyword){
            $bang = false; // 设置不在缓存
            //$where[] = $this->orWhere('username|nickname|mobile', 'like', $keyword);
        }

        // 缓存
        $this->bang = $bang;

        return $where;
    }


}


